/**
 * 部署开发包
 * 
 * 输入参数:
 *   ID:        开发包ID
 *   Package:   开发包内容: {Name, Code, Version, Info, Dependencies, Content, Author, ReleaseTime}
 *   Partial:   指示开发包内容是否仅包含部分内容. 值为true时, 仅执行同步逻辑, 不覆盖开发包数据
 * 
 * 输出参数:
 *   true: 部署成功
 */
(function () {

  function sync_jobs(id, code, jobs = []) {
    A.db.trans('KERNEL', conn => {
      A.db.execute(conn, `DELETE FROM ZY WHERE KFB_ID=?`, [id]);
      jobs.forEach(job => {
        delete A.job[(code ? code + '.' : '') + job.名称];
      });
    });
  }

  function sync_pages(id, pages = []) {
    A.db.trans('KERNEL', conn => {
      A.db.execute(conn, `DELETE FROM YM WHERE KFB_ID=?`, [id]);
    });
  }

  function sync_cards(id, code, cards = [], partial) {
    A.db.trans('KERNEL', conn => {
      A.db.execute(conn, `DELETE FROM KP WHERE KFB_ID=?`, [id]);
      cards.forEach(card => {
        A.db.execute(conn, "DELETE FROM KPSJ WHERE KP_ID=?", [card.ID]);
        A.db.execute(conn, "DELETE FROM KPYY WHERE KP_ID=?", [card.ID]);
        A.db.execute(conn, "DELETE FROM KPSY WHERE KP_ID=?", [card.ID]);

        A.db.connect(card.连接名称, (c_conn) => {
          try {
            A.db.execute(c_conn, "DROP TABLE " + card.标识符);
          } catch (_) { }
        });
        delete A.card[(code ? code + '.' : '') + card.名称];
      });
    });
  }

  function sync_data(id, data_set = {}) {
    Object.keys(data_set).forEach(card_name => {
      try {
        let card = A.card[card_name];
        let records = data_set[card_name];
        records.forEach(record => card.delete(record));
      } catch (e) {
        throw Error(card_name + ': ' + e.message);
      }
    });
  }

  return function ({ UID, ID }) {
    if (!UID) throw Error("未授权的访问");

    // 加载开发包内容
    const { rows: [Package] } = A.db.execute('KERNEL', "SELECT * FROM KFB WHERE ID=?", [ID]);
    if (!Package) throw Error("未找到开发包");

    // 检查是否被依赖
    let { rows } = A.db.execute('KERNEL', "SELECT MC FROM KFB WHERE INSTR(YL, ?) > 0", [ID]);
    if (rows.length > 0) throw Error(`该包正在被${rows.map(r => r.MC).join(',')}包依赖`);

    // 移除内容
    const Code = Package.DM;
    const { Cards, Jobs, Pages, DataSet } = JSON.parse(Package.NR);
    sync_cards(ID, Code, Cards);
    sync_jobs(ID, Code, Jobs);
    sync_pages(ID, Pages);
    sync_data(ID, DataSet);

    A.db.execute('KERNEL', "DELETE FROM KFB WHERE ID=?", [ID]);
    return true;
  };
})()